package cn.newtouch.service.impl;

import cn.newtouch.domain.MovieTicket;
import cn.newtouch.dto.UserMovieDto;
import cn.newtouch.mapper.MovieTicketMapper;
import cn.newtouch.result.JsonResult;
import cn.newtouch.service.IMovieTicketService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lqz
 * @since 2022-09-01
 */
@Service
public class MovieTicketServiceImpl extends ServiceImpl<MovieTicketMapper, MovieTicket> implements IMovieTicketService {

    @Autowired
    private MovieTicketMapper movieTicketMapper;

    //买票
    @Override
    public JsonResult buy(Long userId, Long movieId) {
        //1.根据电影票id查询这种票  判断是否有库存 有库存才能买票
        MovieTicket movieTicket = movieTicketMapper.selectById(movieId);
        if(movieTicket.getStock()==0){
            return JsonResult.error("库存不足！请联系管理员！","10001");
        }
        //2.查询中间表，判断user本身是否有相同的这张票 有就修改票的数量 没有就添加
        UserMovieDto userMovieDto = movieTicketMapper.selectUserMovieByUserIdAndMovieId(userId,movieId);

        if(userMovieDto==null){
            //说明是没有这种票 进行添加操作
            UserMovieDto userMovieDto1 = new UserMovieDto(userId, movieId, 1);
            movieTicketMapper.insertUserMovie(userMovieDto1);
        }else{
            //说明之前有这种票 就在原来基础上加1
            userMovieDto.setCount(userMovieDto.getCount()+1);
            movieTicketMapper.updateUserMovie(userMovieDto);
        }

        //3.购买成功 库存减一
        movieTicket.setStock(movieTicket.getStock()-1);
        updateById(movieTicket);

        return JsonResult.success(movieTicket.getPrice());
    }


    //观看
    @Override
    public JsonResult watch(Long userId, Long movieId) {
        //1.根据电影票id查询是否有该票
        MovieTicket movieTicket = movieTicketMapper.selectById(movieId);
        // 要观看的电影结束时间要大于当前时间
        if(movieTicket.getEndTime().getTime()<new Date().getTime()){
            return JsonResult.error("已过了观影时间，请重新购买其他场次！","10002");
        }
        //2.查询中间表，判断是否有这张票
        UserMovieDto userMovieDto = movieTicketMapper.selectUserMovieByUserIdAndMovieId(userId,movieId);

        if(userMovieDto==null){
            return JsonResult.error("您没有购买这张票！！请先购买后再观影！","10003");
        }else{
            if(userMovieDto.getCount()<1){
                return JsonResult.error("您没有购买这张票！！请先购买后再观影！","10003");
            }
        }
        //票数>1 可以观影 但是自己的票数需要减一
        userMovieDto.setCount(userMovieDto.getCount()-1);
        movieTicketMapper.updateUserMovie(userMovieDto);

        return JsonResult.success("祝您观影愉快！！");

    }
}
